package cn.guoxuepeng.hrm.service.impl;

import cn.guoxuepeng.hrm.client.CourseElasticsearchClient;
import cn.guoxuepeng.hrm.client.SystemdictionaryItemClient;
import cn.guoxuepeng.hrm.controller.dto.IdsDto;
import cn.guoxuepeng.hrm.controller.vo.CourseAddVo;
import cn.guoxuepeng.hrm.domain.CourseByKeyVo;
import cn.guoxuepeng.hrm.domain.*;
import cn.guoxuepeng.hrm.mapper.CourseDetailMapper;
import cn.guoxuepeng.hrm.mapper.CourseMapper;
import cn.guoxuepeng.hrm.mapper.CourseMarketMapper;
import cn.guoxuepeng.hrm.mapper.CourseTypeMapper;
import cn.guoxuepeng.hrm.query.CourseQuery;
import cn.guoxuepeng.hrm.service.ICourseDetailService;
import cn.guoxuepeng.hrm.service.ICourseService;
import cn.guoxuepeng.hrm.util.AjaxResult;
import cn.guoxuepeng.hrm.util.PageList;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author gxp
 * @since 2020-06-18
 */
@Service
public class CourseServiceImpl extends ServiceImpl<CourseMapper, Course> implements ICourseService {

    @Autowired
    private SystemdictionaryItemClient systemdictionaryItemClient;

    @Autowired
    private CourseDetailMapper courseDetailMapper;

    @Autowired
    private ICourseDetailService courseDetailService;

    @Autowired
    private CourseElasticsearchClient courseElasticsearchClient;

    @Autowired
    private CourseMarketMapper courseMarketMapper;

    @Autowired
    private CourseTypeMapper courseTypeMapper;

    /**
     * 连接课程类型表的高级查询和分页
     * @param courseQuery
     * @return
     */
    @Override
    public Page<Course> myPage(CourseQuery courseQuery) {
        return baseMapper.myPage(new Page<Course>(courseQuery.getPageNum(), courseQuery.getPageSize()),courseQuery);
    }

    /**
     * 添加课程信息的基本信息
     * @param courseAddVo
     */
    @Override
    public void add(CourseAddVo courseAddVo) {
        Course course = new Course();
        BeanUtils.copyProperties(courseAddVo,course);
        //查询出对应的数据字典数据里面的课程等级
        SystemdictionaryItem systemdictionaryItem = systemdictionaryItemClient.get(course.getGrade());
        if (systemdictionaryItem!=null){
            //如果不为空就把对应的课程等级赋值给实体类中的课程等级名称
            course.setGradeName(systemdictionaryItem.getName());
        }
        //获取当前登录的用户和该课程所属的租户
        course.setTenantId(26L);
        course.setTenantName("源码时代");
        course.setUserId(42L);
        course.setUserName("admin");
        course.setStatus(0);
        baseMapper.insert(course);
        //把课程详情和简介存入另外一张表
        CourseDetail courseDetail = new CourseDetail();
        BeanUtils.copyProperties(courseAddVo,courseDetail);
        courseDetail.setCourseId(course.getId());
        courseDetailMapper.insert(courseDetail);
    }

    /**
     * 批量上线课程
     * @param dto
     */
    @Override
    public void release(IdsDto dto) {
        List<Long> ids=dto.getIds();
        //修改上线时间和状态
        baseMapper.online(ids,System.currentTimeMillis());
        //查询数据库中的数据
        List<Course> courses = baseMapper.selectBatchIds(ids);
        //上传到es中
        List<CourseAddES> courseDocs = courses2Docs(courses);
        AjaxResult ajaxResult = courseElasticsearchClient.add(courseDocs);
        if(!ajaxResult.isSuccess()){
            //手动回滚事务
            //TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
            throw new RuntimeException(ajaxResult.getMessage());
        }
    }

    /**
     * 课程批量下线
     * @param dto
     * @return
     */
    @Override
    public void offline(IdsDto dto) {
        List<Long> ids=dto.getIds();
        //修改下线时间和状态
        baseMapper.offline(ids,System.currentTimeMillis());
        //删除es
        AjaxResult ajaxResult = courseElasticsearchClient.delete(ids);
        if(!ajaxResult.isSuccess()){
            throw new RuntimeException(ajaxResult.getMessage());
        }
    }

    /**
     * 前台课程的关键字查询
     * @param courseByKeyVo
     */
    @Override
    public AjaxResult findCourseByKey(CourseByKeyVo courseByKeyVo) {
        AjaxResult ajaxResult = courseElasticsearchClient.findCourseByKey(courseByKeyVo);
        return ajaxResult;
    }

    private List<CourseAddES> courses2Docs(List<Course> courses) {
        List<CourseAddES> courseDocs = new ArrayList<>();
        for (Course course : courses) {
            CourseAddES courseDoc = course2Doc(course);
            courseDocs.add(courseDoc);
        }
        return courseDocs;
    }

    private CourseAddES course2Doc(Course course) {
        CourseAddES courseDoc = new CourseAddES();
        //all字段
        CourseType courseType = courseTypeMapper.selectById(course.getCourseTypeId());
        String courseTypeName = "";
        if(courseType!=null){
            courseTypeName = courseType.getName();
        }
        String all = course.getName()+" "+courseTypeName+" "+course.getTenantName();
        courseDoc.setAll(all);

        BeanUtils.copyProperties(course,courseDoc);
        CourseMarket courseMarket = courseMarketMapper.selectOne(new QueryWrapper<CourseMarket>().eq("course_id", course.getId()));
        Float price = 0f;
        if(courseMarket!=null){
            price = courseMarket.getPrice();
        }
        courseDoc.setPrice(price);
        return courseDoc;
    }

}
